import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:intl/intl.dart';
import 'email_model.dart';
import 'email_service.dart';

class EmailDetailPage extends StatefulWidget {
  final Email email;

  const EmailDetailPage({super.key, required this.email});

  @override
  State<EmailDetailPage> createState() => _EmailDetailPageState();
}

class _EmailDetailPageState extends State<EmailDetailPage> {
  late Email _email;
  bool _isDeleting = false;

  @override
  void initState() {
    super.initState();
    _email = widget.email;
    _markAsRead();
  }

  Future<void> _markAsRead() async {
    if (!_email.isRead) {
      await EmailService.markAsRead(_email.id);
      setState(() {
        _email = Email(
          id: _email.id,
          subject: _email.subject,
          sender: _email.sender,
          senderEmail: _email.senderEmail,
          body: _email.body,
          date: _email.date,
          isRead: true,
          attachments: _email.attachments,
        );
      });
    }
  }

  Future<void> _deleteEmail() async {
    setState(() {
      _isDeleting = true;
    });

    try {
      final success = await EmailService.deleteEmail(_email.id);
      if (success) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('邮件已删除')));
        Navigator.of(context).pop(true); // 返回true表示邮件已删除
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('删除邮件失败')));
      }
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('删除邮件时出错: $e')));
    } finally {
      setState(() {
        _isDeleting = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
    final formattedDate = dateFormat.format(_email.date);

    return Scaffold(
      appBar: AppBar(
        title: Text(_email.subject),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Theme.of(context).colorScheme.onPrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.delete),
            onPressed: _isDeleting ? null : _deleteEmail,
          ),
          IconButton(
            icon: const Icon(Icons.reply),
            onPressed: () {
              // 实现回复功能
            },
          ),
          IconButton(
            icon: const Icon(Icons.forward),
            onPressed: () {
              // 实现转发功能
            },
          ),
        ],
      ),
      body:
          _isDeleting
              ? const Center(child: CircularProgressIndicator())
              : SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 邮件头部信息
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              _email.subject,
                              style: const TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Row(
                              children: [
                                CircleAvatar(
                                  backgroundColor:
                                      Theme.of(context).colorScheme.primary,
                                  child: Text(
                                    _email.sender,
                                    style: TextStyle(
                                      color:
                                          Theme.of(
                                            context,
                                          ).colorScheme.onPrimary,
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        _email.sender,
                                        style: const TextStyle(
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Text(_email.senderEmail),
                                    ],
                                  ),
                                ),
                                Text(
                                  formattedDate,
                                  style: TextStyle(color: Colors.grey.shade600),
                                ),
                              ],
                            ),

                            // 附件部分
                            if (_email.attachments != null &&
                                _email.attachments!.isNotEmpty)
                              Padding(
                                padding: const EdgeInsets.only(top: 16.0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text(
                                      '附件',
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    ..._email.attachments!.map((attachment) {
                                      return Card(
                                        child: ListTile(
                                          leading: const Icon(Icons.attachment),
                                          title: Text(attachment.name),
                                          subtitle: Text(
                                            '${_formatFileSize(attachment.size)} - ${attachment.type}',
                                          ),
                                          trailing: IconButton(
                                            icon: const Icon(Icons.download),
                                            onPressed: () {
                                              // 实现下载附件功能
                                            },
                                          ),
                                        ),
                                      );
                                    }).toList(),
                                  ],
                                ),
                              ),
                          ],
                        ),
                      ),
                    ),

                    // 邮件正文
                    const SizedBox(height: 16),
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Html(
                          data: _email.body,
                          // extensions: [],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
    );
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }
}
